package org.hotswap.agent.watch;

import org.hotswap.agent.logging.AgentLogger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author luzhiqing
 * @version 1.0
 * @date 2022/11/10
 */
public class WatchEventListenerManager {

    protected static AgentLogger LOGGER = AgentLogger.getLogger(WatchEventListenerManager.class);

    private static final Map<String, List<WatchEventListener>> LISTENERS = new ConcurrentHashMap<>();

    public static synchronized void addListener(String pathPrefix, WatchEventListener listener) {
        List<WatchEventListener> list = LISTENERS.computeIfAbsent(pathPrefix, k -> new ArrayList<>());
        list.add(listener);
    }

    public static Map<String, List<WatchEventListener>> getListeners() {
        return LISTENERS;
    }

    public static List<WatchEventListener> getListeners(String path) {
        return LISTENERS.get(path);
    }

    public static synchronized void clear() {
        LISTENERS.clear();
    }

    public static synchronized void remove(WatchEventListener eventListener) {
        try {
            for (Iterator<Map.Entry<String, List<WatchEventListener>>> listenersIterator = LISTENERS.entrySet().iterator(); listenersIterator.hasNext(); ) {
                Map.Entry<String, List<WatchEventListener>> pathListenerEntry = listenersIterator.next();
                List<WatchEventListener> l = pathListenerEntry.getValue();

                if (l != null) {
                    l.remove(eventListener);
                }

                if (l == null || l.isEmpty()) {
                    listenersIterator.remove();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Ooops", e);
        }
    }

}
